/**
 * 使用react-intl-universal进行语言切换
 * 使用高阶组件封装，不会刷新页面
 */
import React, { createContext, useState, useEffect } from 'react'
import intl from 'react-intl-universal';
import US from './en-US'
import CN from './zh-CN'
import { getState, setState } from '@/common/state'
import { Select } from 'antd'
const { Option } = Select;
const key = 'language'
const locales = {
    "en-US": US,
    "zh-CN": CN,
    "en_d": require('./en_d.json')
};
export const SUPPOER_LOCALES = [
    {
        name: 'English',
        value: 'en-US'
    },
    {
        name: '简体中文',
        value: 'zh-CN'
    },
    {
        name: '默认',
        value: 'en_d'
    }
];
const ctx = createContext()

/**
 * 容器
 * @param {*} props 
 * @returns 
 */
export function Language(props) {
    const { children } = props
    const [lang, setlang] = useState(getState(key)) // 当前语言
    const [load, setLoad] = useState(false) // 控制加载intl

    useEffect(() => { // 加载 
        let currentLocale = lang
        intl.init({ currentLocale, locales }).then(() => {
            setLoad(true)
            setState(key, lang)
            setlang(currentLocale)
        })
    }, [load])
    return (
        <ctx.Provider value={{
            lang, setlang: val => {
                setLoad(false)
                setlang(val)
            }
        }}>
            {children}
        </ctx.Provider>
    )
}

/**
 * 文本
 * @param {*} props 
 * @returns 
 */
export function Lang(props = {}) { 
    const { str, d = '', params = {} } = props
    return (<ctx.Consumer>
        {() => <>{intl.get(str, params).d(d)}</>}
    </ctx.Consumer>)
}

/**
 * 切换select
 * @param {*} props 
 * @returns 
 */
export function LanguageSelect(props) {
    const { width } = props
    const options = SUPPOER_LOCALES.map(({ name, value }) => <Option key={value} value={value}>{name}</Option>)
    return (
        <ctx.Consumer>
            {({ setlang }) => {
                return (<Select defaultValue={getState(key)} style={{ width }} onChange={(value) => setlang(value)}>
                    {options}
                </Select>)
            }}
        </ctx.Consumer>
    )
}